from django import forms
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.forms.models import model_to_dict
from web.models import Product, ProductBrother, Goods_Image
from web.apis import tools
from django.db.models import Q

# 商品兄弟表单
class ProductBrotherForm(forms.ModelForm):
    class Meta:
        model = ProductBrother
        fields = ['product', 'brother_product']

    def clean_product(self):
        product = self.cleaned_data.get('product')
        if not Product.objects.filter(id=product.id).exists():
            raise forms.ValidationError("商品不存在")
        return product

    def clean_brother_product(self):
        brother_product = self.cleaned_data.get('brother_product')
        if not Product.objects.filter(id=brother_product.id).exists():
            raise forms.ValidationError("兄弟商品不存在")
        return brother_product

    def clean(self):
        cleaned_data = super().clean()
        product = cleaned_data.get('product')
        brother_product = cleaned_data.get('brother_product')

        # 验证不能选择相同的商品
        if product and brother_product and product.id == brother_product.id:
            raise forms.ValidationError("不能选择相同的商品作为兄弟商品")

        # 验证是否已经存在相同的兄弟关系
        if product and brother_product:
            existing = ProductBrother.objects.filter(
                Q(product=product, brother_product=brother_product) |
                Q(product=brother_product, brother_product=product)
            ).exists()
            if existing:
                raise forms.ValidationError("该兄弟关系已存在")

        return cleaned_data

# 创建商品兄弟关系
@csrf_exempt
def create_product_brother(request):
    if request.method == 'POST':
        form = ProductBrotherForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                brother_dict = model_to_dict(form.instance)
                brother_dict['create_time'] = form.instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                brother_dict['update_time'] = form.instance.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='创建商品兄弟关系成功', data=brother_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'创建商品兄弟关系失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 获取商品的所有兄弟商品
@csrf_exempt
def get_product_brothers(request, product_id):
    if request.method == 'GET':
        try:
            product = Product.objects.filter(product_id=product_id).first()
            if not product:
                return JsonResponse(tools.ReturnData(code=400, msg='商品不存在'))

            # 获取作为product的兄弟关系
            brothers_as_product = ProductBrother.objects.filter(product=product)
            # 获取作为brother_product的兄弟关系
            brothers_as_brother = ProductBrother.objects.filter(brother_product=product)

            brother_list = []
            
            # 处理作为product的兄弟关系
            for brother in brothers_as_product:
                brother_product = brother.brother_product
                brother_dict = model_to_dict(brother_product)
                images = []
                for image in Goods_Image.objects.filter(product=brother_product):
                    images.append({
                        'id': image.id,
                        'image': image.image.url,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    })

                brother_dict['create_time'] = brother.create_time.strftime('%Y-%m-%d %H:%M:%S')
                brother_dict['update_time'] = brother.update_time.strftime('%Y-%m-%d %H:%M:%S')
                brother_dict['images'] = images
                brother_list.append(brother_dict)

            # 处理作为brother_product的兄弟关系
            for brother in brothers_as_brother:
                brother_product = brother.product
                brother_dict = model_to_dict(brother_product)
                images = []
                for image in Goods_Image.objects.filter(product=brother_product):
                    images.append({
                        'id': image.id,
                        'image': image.image.url,
                    })
                brother_dict['create_time'] = brother.create_time.strftime('%Y-%m-%d %H:%M:%S')
                brother_dict['update_time'] = brother.update_time.strftime('%Y-%m-%d %H:%M:%S')
                brother_dict['images'] = images
                brother_list.append(brother_dict)

            return JsonResponse(tools.ReturnData(code=200, msg='获取商品兄弟列表成功', data=brother_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取商品兄弟列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 删除商品兄弟关系
@csrf_exempt
def delete_product_brother(request, product_id, brother_id):
    if request.method == 'DELETE':
        try:
            brother = ProductBrother.objects.filter(product_id=product_id, brother_product_id=brother_id).first()
            if not brother:
                return JsonResponse(tools.ReturnData(code=400, msg='商品兄弟关系不存在'))
            
            brother.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除商品兄弟关系成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除商品兄弟关系失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))


# 检查两个商品是否是兄弟关系
@csrf_exempt
def check_product_brother(request, product_id, brother_id):
    if request.method == 'GET':
        try:
            
            if not product_id or not brother_id:
                return JsonResponse(tools.ReturnData(code=400, msg='请提供商品ID和兄弟商品ID'))
            
            # 检查是否存在兄弟关系（双向检查）
            is_brother = ProductBrother.objects.filter(
                Q(product_id=product_id, brother_product_id=brother_id) |
                Q(product_id=brother_id, brother_product_id=product_id)
            ).exists()
            
            return JsonResponse(tools.ReturnData(
                code=200, 
                msg='检查成功',
                data={'is_brother': is_brother}
            ))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'检查商品兄弟关系失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))
